import { ref, watch } from 'vue'

const scrollToBottom = (el) => {
  el.scrollTop = el.scrollHeight + 10
}

const useAutoScrollBottom = (elRef) => {
  const scrollHeight = ref(0)

  let autoToBottom = true
  let updating = false
  let isBottom = false

  const onUpdateElement = () => {
    updating = true
    autoToBottom = isBottom && updating
    if (scrollHeight.value !== elRef.value.scrollHeight) {
      scrollHeight.value = elRef.value.scrollHeight
    }
  }

  const onFinishElement = () => {
    //完成前，需要执行最后一次 onUpdateElement
    onUpdateElement()
    setTimeout(() => resetAutoToBottom(), 100)
  }

  const resetAutoToBottom = () => {
    autoToBottom = true
    updating = false
  }

  const onScroll = (e) => {
    const { scrollTop, clientHeight, scrollHeight } = e.target
    // 判断是否滚动到底部(误差在30以内，都表示到底了)
    isBottom = scrollTop + clientHeight >= scrollHeight - 30
    //
    autoToBottom = isBottom && updating
    //console.log({ autoToBottom, isBottom, updating })
  }

  watch(scrollHeight, () => {
    if (scrollHeight.value > 0 && autoToBottom) {
      scrollToBottom(elRef.value)
    }
  })

  return {
    scrollHeight,
    onUpdateElement,
    onFinishElement,
    onScroll,
    resetAutoToBottom,
  }
}

export { scrollToBottom, useAutoScrollBottom }
